
import Link from 'next/link';
import { observer } from "mobx-react-lite";
import { Button,Avatar, Divider} from 'antd'
import {CodeOutlined,FireOutlined,FolderViewOutlined} from '@ant-design/icons'
import styles from './index.module.scss'
import { prepareConnection } from 'db/index'
import {User,Article } from 'db/entity'
import ListItem from '@/components/ListItem';

export async function getServerSideProps({params}: any) {
  const userId = params?.id
  const db = await prepareConnection()
  const user = await db.getRepository(User).findOne({
    where: { id: Number(userId) }
  })

  const articles = await db.getRepository(Article).find({
    where: { user:{id:Number(userId)} },
    relations:["user","tags"]
  })

  return {
    props: {
      userInfo: JSON.parse(JSON.stringify(user)),
      articles: JSON.parse(JSON.stringify(articles)) || []
    },
  };
}

const UseDetail = (props:any) => {
  const { userInfo={} ,articles=[] } = props
  // 计算总阅读量
  const viewsCount = articles.reduce((pre:any, next:any) => pre + next?.views || 0, 0)

  return (
    <div className={styles.userDetail}>
      <div className={styles.left}>
        <div className={styles.userInfo}>
          <Avatar className={styles.avatar} src={userInfo?.avatar} size={50}></Avatar>
          <div>
            <div className={styles.nickname}>{userInfo?.nickname}</div>
            <div className={styles.desc}>
              <CodeOutlined></CodeOutlined> {userInfo?.job}
            </div>
            <div className={styles.desc}>
              <FireOutlined></FireOutlined> {userInfo?.introduce}
            </div>
          </div>
          <Link href="/user/profile"><Button>编辑个人资料</Button></Link>
        </div>
        <Divider></Divider>
        <div className={styles.article}>
          {
            articles.map((article:any) => (
              <div key={article?.id}>
                <ListItem article={article}></ListItem>
                <Divider></Divider>
              </div>
            )) 
          }
        </div>
      </div>
      <div className={styles.right}>
        <div className={styles.achievement}>
          <div className={styles.header}>个人成就</div>
          <div className={styles.number}>
            <div className={styles.wrapper}>
              <FolderViewOutlined></FolderViewOutlined>
              <span>共创作 {articles?.length} 篇文章</span>
            </div>
            <div className={styles.wrapper}>
              <FolderViewOutlined></FolderViewOutlined>
              <span>文章被阅读 {viewsCount} 次</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  )
}

export default observer(UseDetail)